package com.ze.commontool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;

import com.ze.model.ModelDataMgr;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Handler;
import android.os.Message;

public class UpdateTools {
	static final int connectTimeout = 5 * 60 * 1000;
	static final int readTimeout = 5 * 60 * 1000;
	
	String updateUrl;
	String downloadFileDir;
	String name;
	Proxy mProxy = null;
	public int		fileSize = 0;
	DownloadCallback callback;
	public UpdateTools(DownloadCallback p_callCallback, String p_updateUrl,String p_file, String nameString )
	{
		callback = p_callCallback;
		updateUrl = p_updateUrl;
		downloadFileDir = p_file;
		name = nameString;
	}
	/**
	 * @note  升级后首次打开是否要清空缓存
	 * @param context
	 * 
	 */
	public static String CLEAR_FLAG = "clear1.31";
	public static void installClear(Context context)
	{
		SharedPreferences sharedPreferences = 
			context.getSharedPreferences("update.config", Activity.MODE_WORLD_READABLE);
		if ( sharedPreferences.getBoolean(CLEAR_FLAG, true) )
		{
			LoadImageMgr.getInstance().delAllFile(ModelDataMgr.ROOT_PATH + ModelDataMgr.PHOTO_DIR);
			LoadImageMgr.getInstance().delAllFile(ModelDataMgr.ROOT_PATH + ModelDataMgr.SPACE_DIR);
			LoadImageMgr.getInstance().delAllFile(ModelDataMgr.ROOT_PATH + ModelDataMgr.BLOG_DIR);
			LoadImageMgr.getInstance().delAllFile(ModelDataMgr.ROOT_PATH + ModelDataMgr.ACTIVITY_DIR);
			LoadImageMgr.getInstance().delAllFile(ModelDataMgr.ROOT_PATH + ModelDataMgr.VIDEO_DIR);
			LoadImageMgr.getInstance().delAllFile(ModelDataMgr.ROOT_PATH + ModelDataMgr.PHOTO_LOVE_DIR);
			LoadImageMgr.getInstance().delAllFile(ModelDataMgr.ROOT_PATH + ModelDataMgr.SOUND_DIR);
			LoadImageMgr.getInstance().delAllFile(ModelDataMgr.ROOT_PATH + ModelDataMgr.PIC_CACHE);
			
			context.getSharedPreferences("update.config", Activity.MODE_WORLD_WRITEABLE).edit().
			putBoolean(CLEAR_FLAG, false).commit();
		}
	}
	public void download(Context context, final Handler handler){
			Thread thread = new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					File dir = new File(downloadFileDir);
					File file = new File(downloadFileDir + name);
					if ( !dir.exists() )
					{
						dir.mkdirs();
					}else
					{
						if( file.exists() )
						{
							file.delete();
						}
					}
					boolean bRet = false;
					InputStream is = null;
					FileOutputStream fos = null;
					try {
						file.createNewFile();
						URL url = new URL(updateUrl);
						HttpURLConnection conn = null;
						if (mProxy != null) {
							conn = (HttpURLConnection) url.openConnection(mProxy);
						} else {
							conn = (HttpURLConnection) url.openConnection();
						}
						fileSize =  conn.getContentLength();
						conn.setConnectTimeout(connectTimeout);
						conn.setReadTimeout(readTimeout);
//						conn.setDoInput(true);
						conn.connect();
						is = conn.getInputStream();
						fos = new FileOutputStream(file);
						byte[] temp = new byte[1024];
						int downloadSize = 0;
						int i = 0;
						Message updateProgressMsg ;
						while ((i = is.read(temp)) > 0) {
							fos.write(temp, 0, i);
							downloadSize += i;
							updateProgressMsg = handler.obtainMessage(1);
							updateProgressMsg.arg1 = downloadSize;
							handler.sendMessage(updateProgressMsg);
						}
						fos.flush();
						conn.disconnect();
						bRet = true;
					} catch (Exception e) {
						// TODO Auto-generated catch block
						handler.sendEmptyMessage(-1);
						e.printStackTrace();
					} finally{
						try {
							if( fos!= null )
							{
								fos.close();
								fos = null;
							} 
							if( is != null )
							{
								is.close();
								is = null;
							}
						}catch (Exception e2) {
							// TODO: handle exception
						}
						handler.sendEmptyMessage(2);
					}
				}
			});
			thread.start();
	}
	public Handler handler = new Handler()
	{
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case -1:
				callback.notifyDownError();
				break;
			case 1:
				callback.updateDownloadProgress(msg.arg1);
				break;
			case 2:
				callback.finishDownload();
				break;
			default:
				break;
			}
		};
	};
	// 取得版本号
    public static String GetVersion(Context context) {
		try {
			PackageInfo manager = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			return manager.versionName;
		} catch (NameNotFoundException e) {
			return "Unknown";
		}
	}
	public interface DownloadCallback{
		void finishDownload();
		void notifyDownError();
		void updateDownloadProgress(int cur_size);
	}
}
